package cn.yuemouren.security.core.social.weixin.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @Author: Timi
 * @Description:  Weixin API调用模板， scope为Request的Spring bean, 根据当前用户的accessToken创建。
 * @Date: 2020/6/27 14:47
 * @Version: v1.0
 */
public class WeiXinImpl extends AbstractOAuth2ApiBinding implements WeiXin {

    //获取微信用户url
    private final static String GET_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?openid=";

    //解析类
    private ObjectMapper objectMapper = new ObjectMapper();

    public WeiXinImpl(String accessToken) {
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
    }

    /**
     * 默认注册的StringHttpMessageConverter字符集为ISO-8859-1，而微信返回的是UTF-8的，所以覆盖了原来的方法。
     */
    @Override
    protected List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
        messageConverters.remove(0);
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return messageConverters;
    }
    /**
     * 获取微信用户信息。
     */
    @Override
    public WeixinUserInfo getUserInfo(String openId) {
        String url = GET_USER_INFO_URL + openId;
        String param = getRestTemplate().getForObject(url, String.class);
        if(StringUtils.contains(param,"errorcode")){
            return null;
        }
        WeixinUserInfo userInfo = null;
        try {
            userInfo = objectMapper.readValue(param, WeixinUserInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return userInfo;
    }
}
